package wxutil

import (
	"context"
	"time"

	"zhonghui/console/warehouse/dbx/cache_main"
	"zhonghui/console/warehouse/helperx"
)

func ticketKey(suiteId string) string {
	return "enterpriseWx.suite_ticket_key_prefix" + helperx.EasyMD5(suiteId)
}

func tokenKey(suiteId string) string {
	return "enterpriseWx.suite_access_token_key_prefix" + helperx.EasyMD5(suiteId)
}

func providerKey(corp string) string {
	return "enterpriseWx.provider_access_token_key_prefix" + helperx.EasyMD5(corp)
}

func appKey(corpId string) string {
	return "enterpriseWx.app_access_token_key_prefix" + helperx.EasyMD5(corpId)
}

// GetSuiteTicket 获取SuiteTicket
func GetSuiteTicket(suiteId string) (string, error) {
	return cache_main.Client().Get(context.Background(), ticketKey(suiteId)).Result()
}

// SetSuiteTicket 设置SuiteTicket
func SetSuiteTicket(suiteId string, token string) error {
	return cache_main.Client().Set(context.Background(), ticketKey(suiteId), token, time.Hour*11).Err()
}

// SuiteAccessTokenTtl 获取SuiteAccessToken的有效期
func SuiteAccessTokenTtl(suiteId string) (time.Duration, error) {
	return cache_main.Client().TTL(context.Background(), tokenKey(suiteId)).Result()
}

// SetSuiteAccessToken 设置SuiteAccessToken
func SetSuiteAccessToken(suiteId string, token string) error {
	return cache_main.Client().Set(context.Background(), tokenKey(suiteId), token, time.Second*6000).Err()
}

// GetSuiteAccessToken 获取SuiteAccessToken
func GetSuiteAccessToken(suiteId string) (string, error) {
	return cache_main.Client().Get(context.Background(), tokenKey(suiteId)).Result()
}

func SetProviderAccessToken(corpid, token string) error {
	return cache_main.Client().Set(context.Background(), providerKey(corpid), token, time.Second*6000).Err()
}

func GetProviderAccessToken(corpid string) (string, error) {
	return cache_main.Client().Get(context.Background(), providerKey(corpid)).Result()
}

func GetProviderAccessTokenTtl(corpid string) (time.Duration, error) {
	return cache_main.Client().TTL(context.Background(), providerKey(corpid)).Result()
}

func SetAppAccessToken(corpId, token string) error {
	return cache_main.Client().Set(context.Background(), appKey(corpId), token, time.Second*6000).Err()
}

func GetAppAccessToken(corpId string) (string, error) {
	return cache_main.Client().Get(context.Background(), appKey(corpId)).Result()
}
